package com.sunyard.base.viewModel

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.sunyard.base.api.DemoApiService
import com.sunyard.base.entity.Test
import com.sunyard.base.http.DemoRetrofitFactory
import com.sunyard.base.ktExt.dataConvert

import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.lang.Exception



/**
 * 演示用，可以作为范本
 * */
class BaseDemoViewModel : BaseViewModel() {
    val testModels = MutableLiveData<List<Test>>()

    fun getTestModel() {
        viewModelScope.launch {
            //启动协程 进行网络请求
            try {
                //通过withContext 将数据请求挂入高耗时
                val data = withContext(Dispatchers.IO) {
                    DemoRetrofitFactory.instance.getService(DemoApiService::class.java).getTestApi().dataConvert()
                }
                testModels.value = data
            } catch (e: Exception) {
                //处理异常
                e.printStackTrace()
            }
        }
    }
}